<!-- 分享裂变活动 -->
<template>
	<view class="container" :style="activityJson?.wrapper?.style">
		<view class="tags">
			<view class="tag" v-for="tag in tags" :key="tag.text" @click="toUrl(tag.url)">{{ tag.text }}</view>
		</view>
		<view class="content" :style="activityJson?.content?.style">
			<view :style="activityJson?.content?.title?.style" class="content-title title">{{ activityJson?.content?.title?.text }}</view>
			<!-- 进度条 -->
			<template v-if="vdata.activtiyShare.exchangeType === 0">
				<ProcessBarVue :percent="percent"/>
				<!-- 占位标签 -->
				<view style="height: 46rpx;"></view>
			</template>
			<!-- 被邀请人头像滚动条 -->
			<Marquee v-if="inviteRecords.length <= 5" :marquee-list="inviteRecords" marquee-key="headPic" marquee-type="img"/>
			<!-- 被邀请人头像滚动条 -->
			<MosoweMove v-else :list="inviteRecords">
				<template #default="{ row, rowIndex, colIndex }">
					<image class="mosowe-move-img" v-if="row.headPic" :src="row.headPic"></image>
					<image class="mosowe-move-img" v-else src="@/static/new/user/default-head.png"></image>
				</template>
			</MosoweMove>
			
			<!-- 单奖品 -->
			<template v-if="vdata.activtiyShare.exchangeType === 0">
				<view class="invite-score">助力进度{{ vdata.activtiyShare.successStandardNum }}/{{ vdata.activtiyShare.activityAwardList[0].exchangeShareNum }}人</view>
				<view class="invite-desc">(邀请好友参与活动即可获得奖励)</view>
				<view class="invite-reward">
					<!-- 卡券奖品 -->
					<template v-if="vdata.activtiyShare.activityAwardList[0].awardType === 0">
						<view class="invite-coupon-reward-img">{{ vdata.activtiyShare.activityAwardList[0].awardPrice ? vdata.activtiyShare.activityAwardList[0].awardPrice / 100 : 0 }}元</view>
					</template>
					<!-- 实物奖品 -->
					<template v-else-if="vdata.activtiyShare.activityAwardList[0].awardType === 1">
						<image class="invite-goods-reward-img" :src="vdata.activtiyShare.activityAwardList[0].awardImg" mode="widthFix"></image>
					</template>
					<!-- 福分奖品 -->
					<template v-else-if="vdata.activtiyShare.activityAwardList[0].awardType === 3">
						<view class="invite-score-reward-img">{{ vdata.activtiyShare.activityAwardList[0].awardPrice }}福分</view>
					</template>
				</view>
				
				<button v-if="vdata.activtiyShare.successStandardNum === vdata.activtiyShare.activityAwardList[0].exchangeShareNum" class="invite-btn" plain @click="onExchangeHandle">立即兑换!</button>
				<button v-else-if="!vdata.isLogin" class="invite-btn" plain @click="noLoginPopup">立即邀请!</button>
				<button v-else class="invite-btn" plain open-type="share">立即邀请!</button>
			</template>
			
			<!-- 多奖品 -->
			<template v-else>
				<view class="invite-score">已获得{{ vdata.activtiyShare.successStandardNum }}助力积分，剩余积分{{ vdata.activtiyShare.surplusSuccessNum }}</view>
				<view class="invite-desc">(邀请好友参与活动即可获得积分)</view>
				<button v-if="!vdata.isLogin" class="invite-btn" plain @click="noLoginPopup">立即邀请!</button>
				<button v-else class="invite-btn" plain open-type="share">立即邀请!</button>
				<template v-for="awardInfo in vdata.activtiyShare.activityAwardList">
					<AwardCard :awardInfo="awardInfo" @clickHandle="clickHandle"/>
					<view class="dot-line"></view>
				</template>
			</template>
			
			<view :style="activityJson?.rule?.title?.style" class="rule-title title">{{ activityJson?.rule?.title?.text }}</view>
			
			<view class="invite-rules" :style="activityJson?.rule?.style">
				<text v-if="vdata.activityDetail.remark">{{ vdata.activityDetail.remark?.replace(/\\n/g, "\n") }}</text>
			</view>
		</view>
		<view class="red-line"></view>
	</view>
	
	<!-- 授权登录弹窗 -->
	<gzLoginPopup ref="gzLoginPopupRef" v-model:isLogin="vdata.isLogin" @isLoginCallback="isLoginCallback"></gzLoginPopup>
</template>

<script setup>
	import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
	import { ref, reactive, getCurrentInstance, computed } from "vue"
	import ProcessBarVue from "./components/ProcessBar.vue"
	import Marquee from "./components/Marquee.vue"
	import MosoweMove from './components/MosoweMove.vue'
	import AwardCard from './components/AwardCard.vue'
	import storageManage from '@/util/storageManage.js'
	import { $getActivityHelpDetail, $activityTakePartIn, $activityHelpExchange, $activityHelpRecords } from '@/http/apiManager.js'
	
	// 弹窗封装
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
	
	// 登录弹窗实例
	const gzLoginPopupRef = ref()
	
	// 标签列表
	const tags = [
		// { text: '奖品兑换', url: '' },
		// { text: '排行榜', url: '' },
		{ text: '助力记录', url: '/pagesActivity/ACTE024/helpRecords' },
		// { text: '链接分享', url: '' },
		// { text: '生成海报', url: '' },
	]
	
	// 数据源
	const vdata = reactive({
		isLogin: false,	// 用户是否登录
		activityId: '',	// 活动ID
		activityDetail: {},	// 活动详情
		activtiyShare: {	// 活动分享配置信息
			activityAwardList: [{}],	// 奖品列表
			exchangeType: 0,	// 助力活动类型 0单奖品 2多奖品兑换
			successStandardNum: 0,	// 达标人数
			surplusSuccessNum: 0,	// 当前助力人数
		},
		activityChannelId: null,	// 渠道ID
	})
	
	// 动态计算当前助力百分比
	const percent = computed(() => {
		const { successStandardNum, activityAwardList } = vdata.activtiyShare
		return (successStandardNum / activityAwardList[0].exchangeShareNum * 100).toFixed(2)
	})
	
	const activityJson = ref({
		"wrapper":{
			"style":{
				"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/3c16a284-b6ba-406b-9de1-77b436008f38.png') no-repeat left bottom / 100% 168rpx, url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/159efea8-a4f7-40a4-b7b4-13d171d168f6.png') no-repeat left top / 100% 1232rpx, url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/d7c76e9d-c3d0-4f4e-8fbb-f1cb16ef6b90.png') no-repeat 0 1232rpx / 100% 100%"
			}
		},
		"content":{
			"title":{
				"text":"",
				"style":{
					"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/5333deac-7cb0-4cbd-9ffa-13313a50d6b3.png') no-repeat center top / 278rpx 62rpx"
				}
			},
			"style":{
				"background":"#fff"
			}
		},
		"rule":{
			"title":{
				"text":"",
				"style":{
					"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/8b5701a2-ace0-4835-bb38-724d74e5670a.png') no-repeat center top / 278rpx 62rpx"
				}
			},
			"style":{
				"background":"#FFF6DB"
			}
		}
	})
	
	onLoad(async ({ activityId, activityDetail, activityChannelId }) => {
		vdata.isLogin = storageManage.isLogin()
		vdata.activityId = activityId
		vdata.activityDetail = JSON.parse(decodeURIComponent(activityDetail))
		// 活动动态参数
		activityJson.value = JSON.parse(vdata.activityDetail.activityJson || '{}')
		vdata.activtiyShare.successStandardNum = vdata.activityDetail.activityShareEntity.shareSuccessNum
		// 标题更改为活动名称
		uni.setNavigationBarTitle({
			title: vdata.activityDetail.activityName || '助力得好礼'
		})
		vdata.activityChannelId = activityChannelId
		if (!vdata.isLogin) {
			// 未登录状态下 助力记录展示空
			helpRecordsHandle([])
			// 加载弹窗打开
			uni.showModal({
				title: '提示',
				content: '请先进行登录注册，再进行参与！',
				success({ cancel }) {
					if (cancel) {
						$infoBox.toast('登录失败，无法正常参与活动！')
					} else {
						gzLoginPopupRef.value.open() // 打开授权弹框
					}
				}
			})
			return
		}
		// 请求助力详情
		await getHelpDetail(activityId)
		// 请求助力记录
		await getHelpRecords()
	})
	
	
	
	onShareAppMessage(() => {
		const filterObj = ObjKeyFilter(storageManage.userInfo(),'nickName','headPic','phone')
		return {
			title: vdata.activityDetail.activityShareEntity?.shareText || vdata.activityDetail.activityName || '助力得好礼',
			path: `/pages/welcome/index?share=${JSON.stringify({ ...filterObj, activityHelpId: vdata.activtiyShare.activityHelpId, userId: storageManage.userId(), activityId: vdata.activityId, url: '/pagesActivity/ACTE024/help' })}`,
			imageUrl: vdata.activityDetail.activityShareEntity?.shareImgAppMessage,
		}
	})
	
	// tag标签页面跳转
	function toUrl(url){
		// 判断用户是否登录
		if (!vdata.isLogin){
			gzLoginPopupRef.value.open() // 打开授权弹框
			return
		}
		uni.navigateTo({
			url: `${url}?activityHelpId=${vdata.activtiyShare.activityHelpId}`
		})
	}
	// 前 surplusSuccessNum 后奖品 exchangeShareNum	
	// 请求助力详情
	async function getHelpDetail(activityId){
		const { bizData } = await $getActivityHelpDetail({ activityId })
		if(!bizData){	// 如果没有助力详情数据 则发起新的助力活动
			await inviteHelp(activityId)
		}else{	// 如果有数据
			vdata.activtiyShare = bizData
		}
	}
	// 请求新的助力活动
	async function inviteHelp(activityId){
		const { code } = await $activityTakePartIn({ activityId, activityTemplateNo: 'ACTE024', activityChannelId: vdata.activityChannelId })
		if(code === 40002) return;
		await getHelpDetail(activityId)
	}
	
	// 邀请记录
	const inviteRecords = ref([])
	// 助力记录
	async function getHelpRecords(){
		const { bizData } = await $activityHelpRecords({ activityHelpId: vdata.activtiyShare.activityHelpId })
		// 处理助力记录
		helpRecordsHandle(bizData)
	}
	// 助力记录处理
	function helpRecordsHandle(records){
		// 判断是单奖品还是多奖品 单奖品取 取奖品兑换所需分享次数 多奖品无上限
		let l = 6;
		if(vdata.activtiyShare.exchangeType === 0){	// 单奖品
			l = vdata.activtiyShare.activityAwardList[0].exchangeShareNum
		}else{	// 多奖品
			if(records.length > 6){
				l = records.length
			}
		}
		const tempArr = []
		for (let i = 0; i < l; i++) {
			if(!records[i] || records[i]?.isSuccess !== 1){
				tempArr[i] = { headPic: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/8e9c56cf-8ace-48ec-9ce0-eb6f88a17d11.png' }
			}else{
				tempArr[i] = records[i]
			}
		}
		inviteRecords.value = tempArr
	}
	
	// 未登录弹窗
	function noLoginPopup(){
		gzLoginPopupRef.value.open() // 打开授权弹框
	}
	
	// 助力达标后 兑换奖品 单奖品兑换
	function onExchangeHandle(){
		const { activityHelpId, activityAwardList } = vdata.activtiyShare
		const { activityAwardId, awardName } = activityAwardList[0]
		uni.showModal({
			title: '提示',
			content: `请确认是否兑换【${awardName}】`,
			async success({ cancel }) {
				if(!cancel){
					uni.showLoading({ title: '兑换中...' })
					await $activityHelpExchange({ activityHelpId, activityAwardId });
					await getHelpDetail(vdata.activityId)
					$infoBox.toast('兑换成功')
				}
			}
		})
	}
	
	// 多奖品兑换
	function clickHandle(awardInfo){
		const { activityAwardId, awardName, exchangeShareNum } = awardInfo
		uni.showModal({
			title: '提示',
			content: `请确认是否消耗${exchangeShareNum}积分兑换【${awardName}】`,
			async success({ cancel }) {
				if(!cancel){
					uni.showLoading({ title: '兑换中...' })
					await $activityHelpExchange({ activityHelpId: vdata.activtiyShare.activityHelpId, activityAwardId });
					// 刷新助力详情
					await getHelpDetail(vdata.activityId)
					$infoBox.toast('兑换成功！')
				}
			}
		})
	}
	
	
	// 登录回调
	async function isLoginCallback(){
		if(!vdata.isLogin){
			$infoBox.toast('登录失败，无法正常参与活动！')
		}else{
			// 登陆成功后 亲求助力详情 以及助力记录
			// 请求助力详情
			await getHelpDetail(vdata.activityId)
			// 请求助力记录
			await getHelpRecords()
		}
	}
	
	// 对象属性过滤
	function ObjKeyFilter(obj, ...props){
	    if(!obj || typeof obj!== 'object'){
	        return obj
	    }
	    let newObj = {}
	    for(let key in obj){
	        if(props.includes(key)){
	            newObj[key] = obj[key]
	        }
	    }
	    return newObj
	}
	
</script>

<style lang="less" scoped>
	.dot-line{
		width: 100%;
		border-top: 2rpx dotted #999999;
		margin: 17rpx 0;
	}
	.container{
		width: 100%;
		min-height: 100vh;
		background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/3c16a284-b6ba-406b-9de1-77b436008f38.png'),
						  url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/159efea8-a4f7-40a4-b7b4-13d171d168f6.png'),
						  url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/d7c76e9d-c3d0-4f4e-8fbb-f1cb16ef6b90.png'),;
		background-repeat: no-repeat;
		background-position: 0 100%,0 0, 0 1232rpx;
		background-size: 100% 168rpx, 100% 1232rpx, 100% 100%;
		
		position: relative;
		overflow: hidden;
		padding-bottom: 180rpx;
		
		.tags{
			position: absolute;
			top: 73rpx;
			right: 0;
			display: flex;
			flex-direction: column;
			gap: 14rpx;
			.tag{
				min-width: 120rpx;
				border-radius: 30rpx 0rpx 0rpx 30rpx;
				color: #fff;
				background-color: rgba(0, 0, 0, 0.3);
				font-size: 24rpx;
				padding: 13rpx 0;
				text-align: center;
			}
		}
		
		.content{
			margin: 642rpx 40rpx 0;
			background-color: #FFFFFF;
			border-radius: 20rpx 20rpx 0 0;
			box-shadow: 0 30rpx 30rpx 30rpx #FFF4E9 inset;
			padding: 30rpx 55rpx 60rpx;
			text-align: center;
			position: relative;
			z-index: 2;
			
			.title{
				height: 62rpx;
				margin: 30rpx 0 55rpx;
				
				&.content-title{
					background:url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/5333deac-7cb0-4cbd-9ffa-13313a50d6b3.png') no-repeat center top / 278rpx 62rpx;
				}
				
				&.rule-title{
					margin: 30rpx 0;
					background:url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/8b5701a2-ace0-4835-bb38-724d74e5670a.png') no-repeat center top / 278rpx 62rpx;
				}
			}
			
			
			
			.mosowe-move-img{
				width: 90rpx;
				height: 90rpx;
				display: inline-block;
				margin-right: 28rpx;
				border-radius: 20rpx;
			}
		
			.invite-score{
				font-weight: bold;
				color: #F1AF5A;
				font-size: 36rpx;
				margin-top: 43rpx;
			}
			.invite-desc{
				font-weight: 400;
				font-size: 36rpx;
				margin-top: 33rpx;
			}
			.invite-reward{
				margin-top: 26rpx;
				.invite-goods-reward-img{
					width: 296rpx;
				}
				.invite-coupon-reward-img,.invite-score-reward-img{
					width: 296rpx;
					height: 202rpx;
					background-position: 0 0;
					background-repeat: no-repeat;
					background-size: 100% 100%;
					margin: 0 auto;
					padding-top: 65rpx;
					box-sizing: border-box;
					color: #F8120E;
					font-weight: bold;
					font-size: 36rpx;
				}
				.invite-coupon-reward-img{
					background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/b7d75b1c-1f41-40a6-94ce-632d57cd52c5.png');
				}
				.invite-score-reward-img{
					background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/c2a4a306-82bf-4f05-b6a5-04553bd0b8f5.png');
				}
			}
			.invite-btn{
				border: none;
				background: linear-gradient(180deg, #F78D52, #F93A35);
				max-width: 393rpx;
				border-radius: 45rpx;
				color: #fff;
				font-weight: bold;
				font-size: 45rpx;
				letter-spacing: 5rpx;
				line-height: initial;
				padding: 15rpx 0;
				margin-top: 15rpx;
				margin-bottom: 30rpx;
			}
			
			.invite-rules{
				text-align: left;
				background-color: #FFF6DB;
				border-radius: 10rpx;
				padding: 30rpx 40rpx;
				text{
					font-weight: 400;
				}
			}
			
		}
		.red-line{
			width: calc(100% - 40rpx);
			height: 24rpx;
			background-color: #FB3835;
			border-radius: 24rpx;
			position: relative;
			top: -12rpx;
			left: 20rpx;
			z-index: 1;
		}
	}
</style>